package gen.tools.delivery;

import gen.tools.Widgets;
import gen.tools.structures.InfoStruc;

import java.io.IOException;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mailGenerator.MailSend;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;

public class DeliverFile extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public DeliverFile() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		final boolean isGFLExisted = Boolean.parseBoolean( request.getParameter("isGFLExisted") );		//是否存在共用程式
		final boolean isFURLExisted = Boolean.parseBoolean( request.getParameter("isFURLExisted") );	//是否存在需求下轄程式
		
		int localDeplmainSN = 0;		//部署計畫流水號	交					
		int localDeliverySN = 0;		//交付事件流水號	交
		int reqNum = 0;					//需求數量
		String reqDesc =  "";
		
		final String comment = request.getParameter("delTaskComment");	// 提交時所撰寫的註解
		final String subsysId = request.getParameter("subsysId");
		
		/*	共用程式的清單	*/
		
		/*	解析JSON物件的reference
		 * 	依使用順序分別為
		 * 	1. 共用程式清單 2.	需求下轄程式清單	3. 郵寄人員清單
		 * 	*/
		JsonReader reader = null;
		
		final String jsonDataML = request.getParameter("ml");			//寄件清單
		final String currentUser = request.getParameter("loginUser");
		final String bssId = "MBMS";
		
		int depOrder = 0;	//部署順序
		int comReqsNum = 1;	//此細項包含幾筆需求

		String subject = "【交付通知】"; //信件主旨
		
		final String mHead = "<!DOCTYPE html><html><head><meta charset='UTF-8'><style type='text/css'>body{font-family: 微軟正黑體;}h3{font-family: 標楷體;}tr{font-family: 微軟正黑體;vertical-align:middle;}th {background:#CCCCCC;}td.right {	font-family: Calibri; text-align:right;}td.center {	font-family: Calibri; text-align:center;}	.english_font {		font-family: Calibri,Arial;	}	</style></head><body>";
		StringBuilder mDesc = new StringBuilder("Dears,<p><p>");		//信件開頭的話
		String mReqMapping = "";		//需求與檔案的對應		
		StringBuilder strSQL = new StringBuilder();
		StringBuilder res = new StringBuilder();
		int localSystemId = Integer.parseInt( request.getParameter("localSystemId") );	//本機系統的系統ID
		String localSystemName = request.getParameter("localSystemName");				//取得目前這個系統的名稱
				
		try {
			conn = wid.getConn();
			final int targetSystemId = Integer.parseInt(request.getParameter("targetSystemId"));	//提交對象的系統的身份
			
			mReqMapping = "<p><p><p><h3>上線程式清單</h3><table><tr><th>#</th><th>需求編號</th><th>作業/檔案名稱</th><th>版次("+localSystemName+")</th><th>資訊群組</th></tr>";
			
			/* 部署計畫表頭		交付方  */
			localDeplmainSN = wid.getCurrentSN("deplmain");
			strSQL.replace(0, strSQL.length(), "INSERT INTO deplmain (deplmainSN,sysSN,creator,createdDateTime,subsysid) VALUES ("+localDeplmainSN+",?,?,?,?)");
			ps = conn.prepareStatement( strSQL.toString() );
			ps.setInt(1, localSystemId);
			ps.setString(2, currentUser);
			ps.setTimestamp(3, wid.cDT());
			ps.setString(4, subsysId );
			ps.execute();
			
			/* 交付事件	交付方  
			 * */
			localDeliverySN = wid.getCurrentSN("deltask");
			strSQL.replace(0, strSQL.length(), "INSERT INTO deltask (deliverySN,isDeliver,deliveryComment,deliveryTarSN,deplmainSN,souSysSN,tarSysSN,statusSN) VALUES ("+localDeliverySN+",?,?,?,?,?,?,?)");
			ps = conn.prepareStatement( strSQL.toString() );
			ps.setString(1,"t");
			ps.setString(2, comment );
			ps.setInt(3, 0);
			ps.setInt(4, localDeplmainSN);
			ps.setInt(5, localSystemId);
			ps.setInt(6, targetSystemId);
			ps.setInt(7, 1);	//啟動交付寄發通知中
			ps.execute();
			
			
			/* 信件內容 */
			mDesc.append("交付代碼 ：" + localDeliverySN + "<br>來 源 端： "+localSystemName+"<p><p><p><p>提交人員：");
			subject += localDeliverySN + "- " + localSystemName;
			
			strSQL.replace(0, strSQL.length(), "SELECT empName, empPhone,empEmail FROM emps WHERE empId=?");
			ps = conn.prepareStatement( strSQL.toString() );
			ps.setString(1, currentUser);
			rs = ps.executeQuery();
			rs.next();
			final String currentUserName = rs.getString("empName");
			final String currentEmail = rs.getString("empEmail");
			mDesc.append( currentUserName );
			mDesc.append( "<br>連絡電話：" );
			mDesc.append( rs.getString("empPhone")+"<p><p><p>" );
			mDesc.append( "交付說明：<p><textarea style='border:1' readonly='readonly'>"+comment+"</textarea>"+"<p><p><p><hr>" );
			
			/* 部署計畫細項 (depldetail)  		交付方  */
			int localDepldetailid = 1;	//細項的流水號
			
			/*	共用程式清單	*/
			if ( isGFLExisted ) {	//存在共用程式
				reader = new JsonReader( new StringReader( request.getParameter("gfl") ) );
				
				reader.beginArray();
				while ( reader.hasNext() ) {
					strSQL.replace(0, strSQL.length(), "INSERT INTO depldetail (deplmainSN,depldetailid,localFile,isnonweb,localPath,depPath,localVer,depOrder,comReqsNum,creator,createdDateTime) VALUES (?,?,?,?,?,?,?,?,?,?,?)");
					ps = conn.prepareStatement( strSQL.toString() );
					ps.setInt(1, localDeplmainSN);	
					ps.setInt(2, localDepldetailid);	//細項的流水號
					
					reader.beginObject();	//	開始讀取共用程式
					
					reader.nextName();	//程式名稱
					ps.setString(3, reader.nextString() );
					
					reader.nextName();	//部署方式 web or non-web
					ps.setString(4, "web".equalsIgnoreCase( reader.nextString() )?"f":"t" );
					
					reader.nextName();	//SVN路徑
					ps.setString(5,reader.nextString() );
					
					reader.nextName();	//延伸路徑
					ps.setString(6, reader.nextString() );
					
					reader.nextName();	//版次
					ps.setInt(7, Integer.parseInt( reader.nextString() ) );
					
					depOrder = localDepldetailid;		//部署順序目前先依部署細項的順序依序部署，待UI開發出來後，再行調整
					ps.setInt(8, depOrder);
					
					reader.nextName();	//此細項包含幾筆需求
					comReqsNum = Integer.parseInt( reader.nextString() );
					ps.setInt(9, comReqsNum);
					
					ps.setString(10, currentUser);
					ps.setTimestamp(11, wid.cDT() );
					ps.execute();
					 
					reader.nextName();	/*	資源群組	*/
					reader.beginArray();
					strSQL.replace(0, strSQL.length(), "INSERT INTO mpdeplunitsqu (deplmainSN,depldetailid,bssid,subsysid,squadid,creator,createdDateTime) VALUES (?,?,?,?,?,?,?)");
					/* 記錄程式要部署到那些Squad		交付方 */
					ps = conn.prepareStatement( strSQL.toString() );
					ps.setInt(1, localDeplmainSN);
					ps.setInt(2, localDepldetailid);
					ps.setString(3, bssId);
					ps.setString(6, currentUser);
					ps.setTimestamp(7,wid.cDT());
					while ( reader.hasNext() ) {
						InfoStruc sq = new InfoStruc();
						reader.beginObject();
						reader.nextName(); 
						sq.setId( reader.nextString() );
						ps.setString(4,sq.getId());
						reader.nextName();		//資訊群組ID
						sq.setName( reader.nextString() );
						ps.setString(5,sq.getName());
						reader.endObject();
						ps.execute();
					}
					reader.endArray();	//結束讀取資源群組的陣列
					
					reader.nextName();	/*	需求	*/
					reader.beginArray();
					strSQL.replace(0, strSQL.length(), "INSERT INTO mpreqfiles (deplmainSN,depldetailid,reqSN,creator,createdDateTime) VALUES (?,?,?,?,?)");
					ps = conn.prepareStatement( strSQL.toString() );
					ps.setInt(1, localDeplmainSN);
					ps.setInt(2, localDepldetailid);
					ps.setString(4, currentUser);
					ps.setTimestamp(5,wid.cDT());
					while ( reader.hasNext() ) {
						/*	記錄需求所包含的程式		交付方	*/
						reader.beginObject();
						reader.nextName();
						ps.setInt(3, Integer.parseInt( reader.nextString() )  );	//需求ID
						reader.endObject();
						ps.execute();
					}
					reader.endArray();	//結束讀取需求的陣列
					
					reader.endObject();	//結束讀取共用程式
					localDepldetailid++;	//將細項序號加一
				}
				reader.endArray();
			}
			
			/*	需求下轄程式的清單	*/
			if ( isFURLExisted ) {
				reader = new JsonReader( new StringReader( request.getParameter("furl") ) );
				
				reader.beginArray();		//--1
				while ( reader.hasNext() ) {
					reader.beginObject();	//--2
					reader.nextName();		//需求
					int souReqId = Integer.parseInt( reader.nextString() );
					reqNum++;	//需求數量增加
					
					/*	先自本機的查詢需求詳細資訊	*/
					strSQL.replace(0, strSQL.length(), "SELECT reqDesc FROM reqs WHERE reqId=?");
					ps = conn.prepareStatement( strSQL.toString() );
					ps.setInt(1, souReqId);
					rs = ps.executeQuery();
					rs.next();
					reqDesc =  rs.getString("reqDesc");
					
					/*	查詢目前的流水號	*/
					@SuppressWarnings("unused")
					String tagName = reader.nextName();		//fl	
					reader.beginArray();		//--3		// fl 的Array
					
					ArrayList<FileSquadMapping> fileLists = new ArrayList<FileSquadMapping>();
					
					while( reader.hasNext() )	{	//開始一支支地處理，需求下的每個檔案
						FileSquadMapping flt = new FileSquadMapping();
						strSQL.replace(0, strSQL.length(), "INSERT INTO depldetail (deplmainSN,depldetailid,localFile,isnonweb,localVer,depPath,localPath,creator,createdDateTime) VALUES (?,?,?,?,?,?,?,?,?)");
						ps = conn.prepareStatement( strSQL.toString() );
						ps.setInt(1, localDeplmainSN);	
						ps.setInt(2, localDepldetailid);	//細項的流水號	

						reader.beginObject();		//--4
						reader.nextName();	//	檔案名稱
						flt.setFileName( reader.nextString() );
						ps.setString(3, flt.getFileName() );
						
						reader.nextName();	//	部署方式 web or non-web
						flt.setDepType( reader.nextString() );
						ps.setString(4, "web".equalsIgnoreCase( flt.getDepType() )?"f":"t" );
						
						reader.nextName();	//	版次
						flt.setVer( Integer.parseInt(reader.nextString()) );
						ps.setInt(5, flt.getVer() );
						
						reader.nextName();	//部署路徑
						ps.setString(6, reader.nextString());
						
						reader.nextName();	//SVN路徑
						ps.setString(7,reader.nextString() );
						
						ps.setString(8, currentUser);
						ps.setTimestamp(9,wid.cDT());
						ps.execute();
						
						tagName = reader.nextName();
						reader.beginArray();		//--5
						
						ArrayList<InfoStruc> sqs = new ArrayList<InfoStruc>();
						strSQL.replace(0, strSQL.length(), "INSERT INTO mpdeplunitsqu (deplmainSN,depldetailid,bssid,subsysid,squadid,creator,createdDateTime) VALUES (?,?,?,?,?,?,?)");
						while (reader.hasNext()) {		/* 這筆細項要被部署的資源群組 */
							/* 記錄程式要部署到那些Squad		交付方 */
							ps = conn.prepareStatement( strSQL.toString() );
							ps.setInt(1, localDeplmainSN);
							ps.setInt(2, localDepldetailid);
							ps.setString(3, bssId);

							final InfoStruc sq = new InfoStruc();
							
							reader.beginObject();
							tagName = reader.nextName();
							sq.setId( reader.nextString() );
							ps.setString(4,sq.getId());
							reader.nextName();		//資訊群組ID
							sq.setName(reader.nextString());
							ps.setString(5,sq.getName());
							reader.endObject();
							
							ps.setString(6, currentUser);
							ps.setTimestamp(7,wid.cDT());
							ps.execute();
							
							sqs.add(sq);
						}
						flt.setSquads(sqs);
						
						reader.endArray();		//--5
						reader.endObject();		//--4
						
						/*	記錄需求所包含的程式		交付方	*/
						strSQL.replace(0, strSQL.length(), "INSERT INTO mpreqfiles (deplmainSN,depldetailid,reqSN,creator,createdDateTime) VALUES (?,?,?,?,?)");
						ps = conn.prepareStatement( strSQL.toString() );
						ps.setInt(1, localDeplmainSN);
						ps.setInt(2, localDepldetailid);
						ps.setInt(3, souReqId);
						ps.setString(4, currentUser);
						ps.setTimestamp(5,wid.cDT());
						ps.execute();
						
						localDepldetailid++;	//將細項序號加一
						
						fileLists.add(flt);
					}
					
					/*	信件內容	*/
					mReqMapping += "<tr id='"+souReqId+"'><td class='center english_font' rowspan='"+(fileLists.size()+1)+"'>"+reqNum+"</td></tr>";
					String bgcolor="#CCCCCC";
					int fileNum = 0;
					for (FileSquadMapping isc : fileLists) {
						if ((fileNum%2) ==1) { bgcolor = "#FFFFFF";}
						
						mReqMapping += "<tr bgcolor='"+ bgcolor +"' ><td class='english_font' >"+isc.getFileName()+"</td><td class='english_font right'>"+isc.getVer()+"</td><td class='english_font' ><ul>";
						for (InfoStruc sqs : isc.getSquads()) {
							mReqMapping += "<li>"+sqs.getId()+"-"+sqs.getName()+"</li>";
						}
						mReqMapping += "</ul></td></tr>";
						fileNum++;
					}
				reader.endArray();		//--3
				reader.endObject();		//--2
					
				}
				reader.endArray();	//--1
			}
			
			
			/*	寄發通知信	*/
			mReqMapping += "</table>";
			final String msgBody = mHead+ mDesc.toString() + mReqMapping + "<p><p><p>	<p>-----此為系統通知信，請勿直接回覆-----</body></html>";
			
			final ArrayList<InfoStruc> recipients = new ArrayList<InfoStruc>();
			
			reader = new JsonReader(new StringReader(jsonDataML));
			reader.beginArray();
			while(reader.hasNext()){
				final InfoStruc recipient = new InfoStruc();
				reader.beginObject();
				reader.nextName();
				recipient.setId(reader.nextString());
				reader.nextName();
				recipient.setName(reader.nextString());
				reader.endObject();
				recipients.add(recipient);
			}
			reader.endArray();
			/*final MailSend mailSend = new MailSend();
	        res.replace(0, res.length(), mailSend.sendMailMain(currentEmail, currentUserName,recipients,subject, msgBody) );*/
	        
	        /* 將交付狀態改為2(	完成寄發通知待提領)		交付方 */
			strSQL.replace(0, strSQL.length(), "UPDATE deltask SET statusSN=2 WHERE deliverySN=?");
			ps = conn.prepareStatement( strSQL.toString() );
			ps.setInt(1, localDeliverySN);
			ps.execute();
			
			res.replace(0, res.length(), String.valueOf(localDeliverySN) );
		} catch ( Exception e) {
			wid.errLog(e);
		} finally {
			try {
				if (reader != null) { reader.close(); }
				if (rs != null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) { System.out.println(wid.errProcess(e)); }
		}
		
		response.getWriter().write(new Gson().toJson( res.toString() ));
	
	}

}
